package org.com.app.knock.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.com.app.knock.KnockApplication;
import org.com.app.knock.activity.FriendActivity;
import org.com.app.knock.view.Loading2View;
import org.com.app.knock.view.LoadingView;
import org.com.app.knock.view.SendItemView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import z.lib.base.BaseAdapter;
import z.lib.base.BaseItem;
import z.lib.base.BaseServiceCallBack;
import z.lib.base.BaseUtils;
import z.lib.base.BaseUtils.API;
import z.lib.base.BaseView;
import z.lib.base.CommonAndroid;
import z.lib.base.LogUtils;
import z.lib.base.callback.RestClient.RequestMethod;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.acv.libs.nbase.BaseFragment;
import com.app.lazyload.ImageLoader2;
import com.knock.app.R;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.ParseQuery;

public class SendFragment extends BaseFragment implements AnimationListener {
	protected static final String TAG = "SendFragment";
	private View views;
	GridView listView;
	private BaseAdapter baseAdapter;
	private LoadingView loading;
	private Loading2View loading2;
	public static ImageLoader2 imageLoader;
	LinearLayout setting_main;
	ImageView setting;
	TextView textview;
	RelativeLayout progressbar_main;
	public SendFragment() {
		super();
	}

	@Override
	public void setUpFragment(View view) {
		this.views = view;
		imageLoader = new ImageLoader2(getActivity());
		loading = CommonAndroid.getView(view, R.id.loading);
		loading2 = CommonAndroid.getView(view, R.id.loading2);
		textview = CommonAndroid.getView(loading2, R.id.textview);
		progressbar_main = CommonAndroid.getView(loading2, R.id.progressbar_main);
		CommonAndroid.getView(view, R.id.btn_back).setOnClickListener(this);
		TextView user_send = (TextView) views.findViewById(R.id.mTextView1); 
		user_send.setText(KnockApplication.device_send_username);
		listView =(GridView) views.findViewById(R.id.gridView_item);
		int[] imageId = {
				R.drawable.btn_ms01,
				R.drawable.btn_ms02,
				R.drawable.btn_ms03,
				R.drawable.btn_ms04,
				R.drawable.btn_ms05,
				R.drawable.btn_ms06,
				R.drawable.btn_ms07,
				R.drawable.btn_ms08,
				R.drawable.btn_ms09,
				R.drawable.btn_ms10,
				R.drawable.btn_ms11,
				R.drawable.btn_ms12
		};
//        List<BaseItem> baseItems = new ArrayList<BaseItem>();
//		baseItems.clear();
//		for(int i = 0; i < imageId.length; i++){
//			JSONObject itemObj = new JSONObject();
//		    try
//		    {
//		    	itemObj.put("img_icon", imageId[i]);
//		        baseItems.add(new BaseItem(itemObj));
//		    }catch(Exception e){
//		    }
//		    
//		}
		CommonAndroid.getView(view, R.id.setting).setOnClickListener(this);
		CommonAndroid.getView(view, R.id.send_block).setOnClickListener(this);
		CommonAndroid.getView(view, R.id.send_delete).setOnClickListener(this);
		CommonAndroid.getView(view, R.id.send_cancel).setOnClickListener(this);
		setting_main = (LinearLayout) views.findViewById(R.id.setting_main);
		setting = (ImageView) views.findViewById(R.id.setting);
		//icon avatar
		ImageView imageView = (ImageView) views.findViewById(R.id.avatar);
		imageLoader.DisplayImage2(KnockApplication.device_send_avatar, imageView);
		getIcon();
	}

	private void waitsend(boolean b, String message){
		if(b){
			BaseUtils.playMedia(getActivity(),R.raw.tap_message);
		}
		textview.setText(message);
		progressbar_main.setVisibility(View.GONE);
		textview.setVisibility(View.VISIBLE);
		int secondsDelayed = 2;
		new Handler().postDelayed(new Runnable() {
			public void run() {
				Log.e("TIME::", System.currentTimeMillis() + "");
				CommonAndroid.showView(false, loading2);
			}
		}, secondsDelayed * 1000);
	}
	
	protected void getIcon() {
		// TODO Auto-generated method stub
		HashMap<String, String> params = new HashMap<String, String>();
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_DATA, params, callbackget);
	}
	
	private BaseServiceCallBack callbackget = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				LogUtils.e(TAG,"err=="+message);
			}
		};

		public void onSucces(String response) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				JSONObject mainJsonObject;
				List<BaseItem> baseItems = new ArrayList<BaseItem>();
				baseItems.clear();
				try {
					mainJsonObject = new JSONObject(response);
					JSONArray array = mainJsonObject.getJSONObject("data").getJSONArray("icons");
					for(int i =0; i < array.length();i++){
						baseItems.add(new BaseItem(array.getJSONObject(i)));
					}
					LogUtils.e(TAG,array.toString());
					addView(baseItems);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
	};
	
	@Override
	public int layoytResurce() {
		return R.layout.send;
	}
	
	protected void addView(List<BaseItem> baseItems) {
		// TODO Auto-generated method stub
		baseAdapter = new BaseAdapter(getActivity(), new ArrayList<Object>()) {
			@Override
			public BaseView getView(Context context, Object data) {
				final SendItemView sendItemView = new SendItemView(context);
				return sendItemView;
			}
		};
		baseAdapter.clear();
		baseAdapter.addAllItems(baseItems);
		baseAdapter.notifyDataSetChanged();
		listView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				BaseItem baseItem = (BaseItem) parent.getItemAtPosition(position);
				String img_icon = baseItem.getString("id");
				sendPush(img_icon);
			}
		});
		listView.setAdapter(baseAdapter);
	}
	
	protected void sendPush(String img_icon) {
		// TODO Auto-generated method stub
		progressbar_main.setVisibility(View.VISIBLE);
		textview.setVisibility(View.GONE);
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("friend_id", KnockApplication.device_send_userid);
		params.put("icon_id", img_icon);
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_MESSAGE_ADD, params, callbacksend);
	}
	
	private BaseServiceCallBack callbacksend = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading2);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
//			CommonAndroid.showView(false, loading2);
			if (!isFinish()) {
//				BaseUtils.showDialog(getActivity(), "" + message);
				waitsend(false, message);
			}
		};

		public void onSucces(String response) {
//			CommonAndroid.showView(false, loading2);
			if (!isFinish()) {
				JSONObject mainJsonObject;
				try {
					mainJsonObject = new JSONObject(response);
					String message = CommonAndroid.getString(mainJsonObject,
							BaseUtils.KEY.err_msg);
					LogUtils.e(TAG,"send push"+ mainJsonObject.toString());
//					BaseUtils.showDialog(getActivity(), "" + message);
					String message2 = getString(R.string.send_push_wait);
					waitsend(true, message2);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
	};


	@Override
	public void onClick(View v) {
		super.onClick(v);
		int idView = v.getId();
		switch (idView) {
		case R.id.btn_back:
//			startFragment(new Friend_oldFragment(), null);
			getActivity().finish();
			break;
		case R.id.add_friends:
			
			break;
		case R.id.setting:
			setting_main.setVisibility(View.VISIBLE);
			setting.setVisibility(View.GONE);
			listView.setEnabled(false);
			break;
		case R.id.send_block:
			BaseUtils.playMedia(getActivity(),R.raw.delete);
			setting_main.setVisibility(View.GONE);
			setting.setVisibility(View.GONE);
			listView.setEnabled(true);
			blockFriend(KnockApplication.device_send_userid);
			break;	
		case R.id.send_delete:
			BaseUtils.playMedia(getActivity(),R.raw.delete);
			setting_main.setVisibility(View.GONE);
			setting.setVisibility(View.GONE);
			listView.setEnabled(true);
			deleteFriend(KnockApplication.device_send_userid);
			break;	
		case R.id.send_cancel:
			setting_main.setVisibility(View.GONE);
			setting.setVisibility(View.VISIBLE);
			listView.setEnabled(true);
			break;	
		default:
			break;
		}
	}

	protected void deleteFriend(String id) {
		// TODO Auto-generated method stub
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("friend_id", id);
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_FRIEND_REMOVE, params, callbackdelete);
	}
	
	private BaseServiceCallBack callbackdelete = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				setting.setVisibility(View.VISIBLE);
				BaseUtils.showDialog(getActivity(), "" + message);
			}
		};

		public void onSucces(String response) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				getActivity().finish();
			}
		};
	};
	
	protected void blockFriend(String id) {
		// TODO Auto-generated method stub
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("friend_id", id);
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_FRIEND_BLOCK, params, callbackblock);
	}
	
	private BaseServiceCallBack callbackblock = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				setting.setVisibility(View.VISIBLE);
				BaseUtils.showDialog(getActivity(), "" + message);
			}
		};

		public void onSucces(String response) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				getActivity().finish();
			}
		};
	};
	
	@Override
	public void onAnimationStart(Animation animation) {

	}

	@Override
	public void onAnimationEnd(Animation animation) {
		mHandle.sendEmptyMessage(0);
	}

	@Override
	public void onAnimationRepeat(Animation animation) {

	}
}